$(function () {
    let goodsId = getQueryString("goodsId");
    let url = '../product/list';
    if (goodsId) {
        url += '?goodsId=' + goodsId;
    }
    $("#jqGrid").Grid({
        url: url,
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true, hidden: true},
            {label: '商品名称', name: 'goodsName', index: 'goods_id', width: 120},
            {label: '商品序列号', name: 'goodsSn', index: 'goods_sn', width: 80},
            {
                label: '商品规格',
                name: 'specificationsName',
                index: 'goods_specification_ids',
                width: 100,
                formatter: function (value, options, row) {
                    return value.replace(row.goodsName + " ", '');
                }
            },
            {label: '商品库存数', name: 'goodsNumber', index: 'goods_number', width: 80}]
    });
});

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        product: {},
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ],
            goodsSn: [
                {required: true, message: '序列号不能为空', trigger: 'blur'}
            ],
            goodsNumber: [
                {required: true, validator:validateInteger,trigger: 'blur'}
            ]
        },
        q: {
            goodsName: ''
        },
        goodsList: [],
        selectedSpecification: [],
        type: '', //判断是新增还是修改操作
        specifications: [], //规格项列表，中大团队扩展
        specificationItems: [], //所有规格项的下拉列表，中大团队扩展
        checkedSpecificationsStr: '#',   //用于记录已经选择过的规格，以#进行分割，中大团队扩展
        partSpecifications: []  //选中的多个规格项

    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.product = {};
            vm.type = 'add';
            vm.clearFormState();
            vm.getGoodsList();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.type = 'update';
            vm.clearFormState();
            vm.getProductInfo(id);
        },
        changeGoods: function (opt) {
            let goodsId = opt.value;
            if(!goodsId)return;

            Ajax.request({
                url: "../goods/info/" + goodsId,
                async: true,
                successCallback: function (r) {
                    if (vm.type == 'add') {
                        vm.product.goodsSn = r.goods.goodsSn;
                        vm.product.goodsNumber = r.goods.goodsNumber;
                        vm.product.retailPrice = r.goods.retailPrice;
                        vm.product.marketPrice = r.goods.marketPrice;
                    }

                    //中大团队扩展，动态获取商品规格配置
                    Ajax.request({
                        url: "../specification/getSpecificationsByGoodsId?goodsId="+goodsId,
                        async: true,
                        successCallback: function (r) {
                            vm.specifications = r.list;
                            vm.clearFormState();
                        }
                    });
                }
            });
        },
        clearFormState: function(){
            //清空相关状态值
            vm.selectedSpecification = [];
            vm.specificationItems = [];
            vm.checkedSpecificationsStr = "";
            vm.partSpecifications = [];
        },
        getSpecificationItems: function(data) {
            if(data.length > 0){
                //需要获取下拉列表的规格项
                var specificationId;
                var idx = 0;

                for(var i=0; i<data.length; i++) {
                    if(vm.selectedSpecification.indexOf("#"+data[i]+"#") < 0) {
                        specificationId = data[i];
                        idx = i;
                        vm.checkedSpecificationsStr += data[i] + "#";
                    }
                }

                if(specificationId) {
                    Ajax.request({
                        url: "../goodsspecification/queryAll?goodsId=" + vm.product.goodsId + "&specificationId=" + specificationId,
                        async: true,
                        successCallback: function (r) {
                            vm.specificationItems[idx] = r.list;

                            //更改并复原selectedSpecification值，触发页面下拉框刷新
                            var copy = vm.selectedSpecification.slice(0);
                            vm.selectedSpecification = [];
                            vm.selectedSpecification = copy;
                        }
                    });
                }
            }
        },
        saveOrUpdate: function (event) {
            let url = vm.product.id == null ? "../product/save" : "../product/update";

            //检查库存数
            if(!vm.product.goodsNumber || vm.product.goodsNumber == 0){
                alert("库存设置不正确，请选择所有规格后再录入大于零的库存数！");
                return;
            }

            //计算规格字符串
            var goodsSpecificationIds = "";
            if(vm.partSpecifications && vm.partSpecifications.length > 0){
                for(var i=0; i<vm.partSpecifications.length; i++){
                    goodsSpecificationIds += vm.partSpecifications[i] + "_";
                }
                vm.product.goodsSpecificationIds = goodsSpecificationIds;
            }

            //提交表单数据
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.product),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
		saveOrUpdateAndNext: function (event) {
            let url = vm.product.id == null ? "../product/save" : "../product/update";

			//检查库存数
            if(!vm.product.goodsNumber || vm.product.goodsNumber == 0){
                alert("库存设置不正确，请选择所有规格后再录入大于零的库存数！");
                return;
            }

            //计算规格字符串
            var goodsSpecificationIds = "";
            if(vm.partSpecifications && vm.partSpecifications.length > 0){
                for(var i=0; i<vm.partSpecifications.length; i++){
                    goodsSpecificationIds += vm.partSpecifications[i] + "_";
                }
                vm.product.goodsSpecificationIds = goodsSpecificationIds;
            }
            console.info(JSON.stringify(vm.product));

            //提交表单数据
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.product),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        //vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../product/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getProductInfo: function (id) {
            Ajax.request({
                url: "../product/getInfoDetail/" + id,
                async: true,
                successCallback: function (r) {
                    vm.product = r.product;
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'goodsName': vm.q.goodsName},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
		handleSubmitAndNext: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdateAndNext()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getGoodsList: function () {
            Ajax.request({
                url: "../goods/queryAll/",
                async: true,
                successCallback: function (r) {
                    vm.goodsList = r.list;
                }
            });
        }
    }
});